import { LOGIN_TOKEN } from '@/global/Constances'
import router from '@/router'
import { accountLoginRequest, getUserInfoById, getUserMenusByRoleId } from '@/service/login/login'
import type { IAccount } from '@/types/login'
import { localCache } from '@/utils/cache'
import { mapMenusToRotes } from '@/utils/map-menus'
import { ElMessage } from 'element-plus'
import { defineStore } from 'pinia'
import useMainStore from '../main/main'
import { mapMenusToPermissions } from '@/utils/map-menus'

interface ILoginState {
  token: string
  userInfo: any
  userMenus: any
  permissions: string[]
}

const useLoginStore = defineStore('login', {
  state: (): ILoginState => ({
    token: '',
    userInfo: {},
    userMenus: [],
    permissions: []
  }),
  actions: {
    async loginAccountAction(account: IAccount) {
      // 账号登录，获取token等信息
      const loginData = await accountLoginRequest(account)
      // console.log(loginData)
      if (loginData.data) {
        const id = loginData.data.id
        this.token = loginData.data.token

        // 进行本地缓存
        localCache.setCache(LOGIN_TOKEN, this.token)

        // 获取登录用户的详细信息(role信息)
        const userInfoResult = await getUserInfoById(id)
        const userInfo = userInfoResult.data
        this.userInfo = userInfo
        // console.log(this.userInfo.role)

        // 根据角色请求用户的权限
        const userMenusResult = await getUserMenusByRoleId(this.userInfo.role.id)
        const userMenus = userMenusResult.data
        this.userMenus = userMenus
        // console.log(this.userMenus)

        // 进行本地缓存
        localCache.setCache('userInfo', userInfo)
        localCache.setCache('userMenus', userMenus)

        // 请求所有的roles和departments数据
        const mainStore = useMainStore()
        mainStore.fetchEntireDataAction()

        // 获取按钮的权限
        const permissions = mapMenusToPermissions(userMenus)
        this.permissions = permissions

        // 重要：动态的添加路由，由于在这加，刷新后添加到动态路由就失效了,所以除这里外还要在其他地方加,
        // 这里要加的原因是登录那一次没有token,其他地方有个判断token的,没有token是不会执行,所以其他地方加是只有刷新或者存在token的时候有用
        // 1:可以在router文件夹面的index.ts里面加，
        // 2:也可以在main.ts里面加
        const routeItems = mapMenusToRotes(userMenus)
        // console.log(routeItems)
        routeItems.forEach((item) => {
          router.addRoute('main', item)
        })

        // 登录成功，路由跳转
        router.push('/main')

        // console.log(loginData)
      } else {
        ElMessage.error('账号或密码错误，请重新输入~~')
      }
    },

    loadLocalCacheAction() {
      // 用户进行刷新默认加载数据
      const token = localCache.getCache(LOGIN_TOKEN)
      const userInfo = localCache.getCache('userInfo')
      const userMenus = localCache.getCache('userMenus')
      if (token && userInfo && userMenus) {
        this.token = token
        this.userInfo = userInfo
        this.userMenus = userMenus

        // 请求所有的roles和departments数据
        const mainStore = useMainStore()
        mainStore.fetchEntireDataAction()

        // 获取按钮的权限
        const permissions = mapMenusToPermissions(userMenus)
        this.permissions = permissions

        // 动态添加路由
        const routeItems = mapMenusToRotes(userMenus)
        routeItems.forEach((item) => {
          router.addRoute('main', item)
        })
      }
    }
  }
})

export default useLoginStore
